// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package user

import (
	"audio-server/internal/model"
	"audio-server/internal/sqlutil"
	"audio-server/internal/svc"
	"audio-server/internal/types"
	"context"
	"database/sql"
	"encoding/json"

	"github.com/zeromicro/go-zero/core/logx"
)

type SaveUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSaveUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveUserLogic {
	return &SaveUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SaveUserLogic) SaveUser(req *types.UserSaveReq) (resp bool, err error) {
	key, err := sqlutil.GenerateAPIKey()
	if err != nil {
		return false, err
	}
	user := &model.Users{
		Username:    req.Username,
		Nickname:    req.Nickname,
		Gender:      int64(req.Gender),
		Avatar:      req.Avatar,
		ApiKey:      key,
		Description: sql.NullString{String: req.Description, Valid: true},
	}
	password, err := sqlutil.HashPassword("123456")
	if err != nil {
		return false, err
	}

	user.Password = password
	jsonData, err := json.Marshal(req.RoleIds)
	user.RoleIds = string(jsonData)
	userModel := model.NewUsersModel(l.svcCtx.Conn)
	_, err = userModel.Insert(l.ctx, user)

	if err != nil {
		return false, err
	}
	return true, err
}
